package com.fushenlan.util;

import com.alibaba.fastjson.JSON;
import com.fushenlan.dto.QRCodeDTO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @author: coolman
 * @date: 2022/05/14 12:26
 * @Description: Java生成二维码
 */
public class QRCodeGenerator {
    //二维码图片的宽度
    private static int WIDTH = 300;
    //二维码图片的高度
    private static int HEIGHT = 300;

    public static void generateQRCodeImage(OutputStream stream, String str) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//H最高容错等级
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(str, BarcodeFormat.QR_CODE, WIDTH, HEIGHT,hints);

        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", stream);

    }

    public static void main(String[] args) throws Exception{
        QRCodeDTO qrCodeDTO=new QRCodeDTO();
        qrCodeDTO.setKey("fslnb");
        qrCodeDTO.setValue(9527l);
        String str=JSON.toJSONString(qrCodeDTO);
        byte[] data = null;
        ByteArrayOutputStream stream=new ByteArrayOutputStream ();
        generateQRCodeImage(stream,str);
        data = stream.toByteArray();
        stream.close();
        System.out.println(new String(Base64.encodeBase64(data)));
    }

}
